const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const OSS = require('ali-oss');

const router = express.Router();

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../public/uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 获取当前日期目录名（格式：YYYYMMDD）
const getDateDir = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}${month}${day}`;
};

// 配置multer存储（本地）
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    // 创建日期目录
    const dateDir = getDateDir();
    const targetDir = path.join(uploadDir, dateDir);
    
    // 确保日期目录存在
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true });
    }
    
    cb(null, targetDir);
  },
  filename: (req, file, cb) => {
    // 生成唯一文件名：时间戳 + uuid + 原扩展名
    const ext = path.extname(file.originalname);
    const filename = `${Date.now()}-${uuidv4()}${ext}`;
    cb(null, filename);
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  // 允许的图片类型
  const allowedMimes = [
    'image/jpeg',
    'image/jpg', 
    'image/png',
    'image/gif',
    'image/webp'
  ];
  
  if (allowedMimes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('不支持的文件类型，只允许上传图片文件'), false);
  }
};

// 配置multer
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB限制
    files: 10 // 最多10个文件
  },
  fileFilter: fileFilter
});

// OSS客户端配置
let ossClient = null;

// 初始化OSS客户端
const initOSSClient = () => {
  if (ossClient) return ossClient;
  
  const { 
    OSS_REGION = 'oss-cn-hangzhou',
    OSS_ACCESS_KEY_ID,
    OSS_ACCESS_KEY_SECRET,
    OSS_BUCKET = 'second-hand-uploads',
    OSS_ENDPOINT
  } = process.env;
  
  if (!OSS_ACCESS_KEY_ID || !OSS_ACCESS_KEY_SECRET) {
    console.warn('⚠️ OSS配置不完整，OSS上传功能将不可用');
    return null;
  }
  
  try {
    ossClient = new OSS({
      region: OSS_REGION,
      accessKeyId: OSS_ACCESS_KEY_ID,
      accessKeySecret: OSS_ACCESS_KEY_SECRET,
      bucket: OSS_BUCKET,
      endpoint: OSS_ENDPOINT
    });
    
    console.log('✅ OSS客户端初始化成功');
    return ossClient;
  } catch (error) {
    console.error('❌ OSS客户端初始化失败:', error.message);
    return null;
  }
};

// 上传到OSS
const uploadToOSS = async (fileBuffer, filename, contentType) => {
  const client = initOSSClient();
  if (!client) {
    throw new Error('OSS客户端未初始化');
  }
  
  try {
    const result = await client.put(filename, fileBuffer, {
      headers: {
        'Content-Type': contentType
      }
    });
    
    return {
      url: result.url,
      filename: filename,
      size: fileBuffer.length
    };
  } catch (error) {
    throw new Error(`OSS上传失败: ${error.message}`);
  }
};

// 从OSS删除文件
const deleteFromOSS = async (filename) => {
  const client = initOSSClient();
  if (!client) {
    throw new Error('OSS客户端未初始化');
  }
  
  try {
    await client.delete(filename);
    return true;
  } catch (error) {
    throw new Error(`OSS删除失败: ${error.message}`);
  }
};

// 检查OSS是否可用
const isOSSEnabled = () => {
  return !!initOSSClient();
};

// 单文件上传（本地存储）
router.post('/single', upload.single('image'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        code: 400,
        message: '请选择要上传的图片',
        success: false
      });
    }

    // 获取当前日期目录
    const dateDir = getDateDir();
    
    // 构建图片访问URL（包含日期目录）
    const imageUrl = `/uploads/${dateDir}/${req.file.filename}`;
    
    res.json({
      code: 200,
      message: '图片上传成功（本地存储）',
      success: true,
      data: {
        filename: req.file.filename,
        originalName: req.file.originalname,
        size: req.file.size,
        mimetype: req.file.mimetype,
        url: imageUrl,
        dateDir: dateDir,
        storage: 'local'
      }
    });
  } catch (error) {
    console.error('图片上传错误:', error);
    res.status(500).json({
      code: 500,
      message: '图片上传失败',
      success: false
    });
  }
});

// 单文件上传到OSS
router.post('/oss/single', upload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        code: 400,
        message: '请选择要上传的图片',
        success: false
      });
    }

    if (!isOSSEnabled()) {
      return res.status(500).json({
        code: 500,
        message: 'OSS服务不可用，请检查配置',
        success: false
      });
    }

    // 读取文件内容
    const fileBuffer = fs.readFileSync(req.file.path);
    
    // 上传到OSS
    const ossResult = await uploadToOSS(fileBuffer, req.file.filename, req.file.mimetype);
    
    // 删除本地临时文件
    fs.unlinkSync(req.file.path);
    
    res.json({
      code: 200,
      message: '图片上传到OSS成功',
      success: true,
      data: {
        filename: req.file.filename,
        originalName: req.file.originalname,
        size: req.file.size,
        mimetype: req.file.mimetype,
        url: ossResult.url,
        storage: 'oss'
      }
    });
  } catch (error) {
    console.error('OSS上传错误:', error);
    
    // 删除本地临时文件
    if (req.file && fs.existsSync(req.file.path)) {
      fs.unlinkSync(req.file.path);
    }
    
    res.status(500).json({
      code: 500,
      message: `OSS上传失败: ${error.message}`,
      success: false
    });
  }
});

// 多文件上传（本地存储）
router.post('/multiple', upload.array('images', 10), (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '请选择要上传的图片',
        success: false
      });
    }
    
    // 获取当前日期目录
    const dateDir = getDateDir();
    
    const uploadedFiles = req.files.map(file => ({
      filename: file.filename,
      originalName: file.originalname,
      size: file.size,
      mimetype: file.mimetype,
      url: `/uploads/${dateDir}/${file.filename}`,
      dateDir: dateDir,
      storage: 'local'
    }));

    res.json({
      code: 200,
      message: `成功上传 ${uploadedFiles.length} 张图片（本地存储）`,
      success: true,
      data: uploadedFiles
    });
  } catch (error) {
    console.error('多图片上传错误:', error);
    res.status(500).json({
      code: 500,
      message: '图片上传失败',
      success: false
    });
  }
});

// 多文件上传到OSS
router.post('/oss/multiple', upload.array('images', 10), async (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '请选择要上传的图片',
        success: false
      });
    }

    if (!isOSSEnabled()) {
      return res.status(500).json({
        code: 500,
        message: 'OSS服务不可用，请检查配置',
        success: false
      });
    }

    const uploadedFiles = [];
    
    // 批量上传到OSS
    for (const file of req.files) {
      try {
        const fileBuffer = fs.readFileSync(file.path);
        const ossResult = await uploadToOSS(fileBuffer, file.filename, file.mimetype);
        
        uploadedFiles.push({
          filename: file.filename,
          originalName: file.originalname,
          size: file.size,
          mimetype: file.mimetype,
          url: ossResult.url,
          storage: 'oss'
        });
        
        // 删除本地临时文件
        fs.unlinkSync(file.path);
      } catch (error) {
        console.error(`文件 ${file.originalname} 上传失败:`, error);
        // 继续处理其他文件
      }
    }

    if (uploadedFiles.length === 0) {
      return res.status(500).json({
        code: 500,
        message: '所有文件上传失败',
        success: false
      });
    }

    res.json({
      code: 200,
      message: `成功上传 ${uploadedFiles.length} 张图片到OSS`,
      success: true,
      data: uploadedFiles
    });
  } catch (error) {
    console.error('多文件OSS上传错误:', error);
    
    // 清理所有本地临时文件
    if (req.files) {
      req.files.forEach(file => {
        if (fs.existsSync(file.path)) {
          fs.unlinkSync(file.path);
        }
      });
    }
    
    res.status(500).json({
      code: 500,
      message: `OSS上传失败: ${error.message}`,
      success: false
    });
  }
});

// 获取上传的图片（支持日期目录结构）
router.get('/images/:dateDir/:filename', (req, res) => {
  try {
    const dateDir = req.params.dateDir;
    const filename = req.params.filename;
    
    // 安全检查：防止目录遍历攻击
    if (dateDir.includes('..') || dateDir.includes('/') || dateDir.includes('\\') ||
        filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
      return res.status(400).json({
        code: 400,
        message: '无效的文件路径',
        success: false
      });
    }
    
    // 验证日期目录格式（YYYYMMDD）
    if (!/^\d{8}$/.test(dateDir)) {
      return res.status(400).json({
        code: 400,
        message: '无效的日期目录格式',
        success: false
      });
    }
    
    const filePath = path.join(uploadDir, dateDir, filename);
    
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        code: 404,
        message: '图片不存在',
        success: false
      });
    }
    
    // 设置适当的Content-Type
    const ext = path.extname(filename).toLowerCase();
    const mimeTypes = {
      '.jpg': 'image/jpeg',
      '.jpeg': 'image/jpeg',
      '.png': 'image/png',
      '.gif': 'image/gif',
      '.webp': 'image/webp'
    };
    
    const contentType = mimeTypes[ext] || 'application/octet-stream';
    res.setHeader('Content-Type', contentType);
    
    // 设置缓存头
    res.setHeader('Cache-Control', 'public, max-age=86400'); // 缓存1天
    
    // 发送文件
    res.sendFile(filePath);
  } catch (error) {
    console.error('获取图片错误:', error);
    res.status(500).json({
      code: 500,
      message: '获取图片失败',
      success: false
    });
  }
});

// 删除图片（本地存储，支持日期目录结构）
router.delete('/images/:dateDir/:filename', (req, res) => {
  try {
    const dateDir = req.params.dateDir;
    const filename = req.params.filename;
    
    // 安全检查
    if (dateDir.includes('..') || dateDir.includes('/') || dateDir.includes('\\') ||
        filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
      return res.status(400).json({
        code: 400,
        message: '无效的文件路径',
        success: false
      });
    }
    
    // 验证日期目录格式（YYYYMMDD）
    if (!/^\d{8}$/.test(dateDir)) {
      return res.status(400).json({
        code: 400,
        message: '无效的日期目录格式',
        success: false
      });
    }
    
    const filePath = path.join(uploadDir, dateDir, filename);
    
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        code: 404,
        message: '图片不存在',
        success: false
      });
    }
    
    // 删除文件
    fs.unlinkSync(filePath);
    
    res.json({
      code: 200,
      message: '图片删除成功',
      success: true
    });
  } catch (error) {
    console.error('删除图片错误:', error);
    res.status(500).json({
      code: 500,
      message: '删除图片失败',
      success: false
    });
  }
});

// 删除OSS图片
router.delete('/oss/images/:filename', async (req, res) => {
  try {
    const filename = req.params.filename;
    
    // 安全检查
    if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
      return res.status(400).json({
        code: 400,
        message: '无效的文件名',
        success: false
      });
    }
    
    if (!isOSSEnabled()) {
      return res.status(500).json({
        code: 500,
        message: 'OSS服务不可用，请检查配置',
        success: false
      });
    }
    
    await deleteFromOSS(filename);
    
    res.json({
      code: 200,
      message: 'OSS图片删除成功',
      success: true
    });
  } catch (error) {
    console.error('删除OSS图片错误:', error);
    res.status(500).json({
      code: 500,
      message: `删除OSS图片失败: ${error.message}`,
      success: false
    });
  }
});

// 检查OSS状态
router.get('/oss/status', (req, res) => {
  try {
    const enabled = isOSSEnabled();
    
    res.json({
      code: 200,
      message: enabled ? 'OSS服务正常' : 'OSS服务不可用',
      success: true,
      data: {
        enabled: enabled,
        config: {
          region: process.env.OSS_REGION || 'oss-cn-hangzhou',
          bucket: process.env.OSS_BUCKET || 'second-hand-uploads',
          endpoint: process.env.OSS_ENDPOINT || '未设置'
        }
      }
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '检查OSS状态失败',
      success: false
    });
  }
});

// 错误处理中间件
router.use((error, req, res, next) => {
  if (error instanceof multer.MulterError) {
    if (error.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({
        code: 400,
        message: '文件大小超过限制（最大10MB）',
        success: false
      });
    }
    if (error.code === 'LIMIT_FILE_COUNT') {
      return res.status(400).json({
        code: 400,
        message: '上传文件数量超过限制',
        success: false
      });
    }
  }
  
  res.status(500).json({
    code: 500,
    message: error.message || '上传过程发生错误',
    success: false
  });
});

module.exports = router;